package com.fmdj.mis.api.controller;
import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.annotation.SaMode;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.fmdj.common.util.CommonResult;
import com.fmdj.common.util.PageUtils;

import com.fmdj.mis.api.controller.form.*;
import com.fmdj.mis.api.db.pojo.UserEntity;
import com.fmdj.mis.api.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.*;

@RestController
@RequestMapping("/user")
@Tag(name = "UserController", description = "用户Web接口")
public class UserController {

    @Resource
    private UserService userService;

    /**
     * 登陆成功后加载用户的基本信息
     */
//    @GetMapping("/loadUserInfo")
//    @Operation(summary = "登陆成功后加载用户的基本信息")
//    @SaCheckLogin
//    public CommonResult loadUserInfo() {
//        int userId = StpUtil.getLoginIdAsInt();
//        HashMap summary = userService.loadUserInfo(userId);
//        return CommonResult.ok(summary);
//    }
//
//
//    @PostMapping("/selectById")
//    @Operation(summary = "根据ID查找用户")
//    @SaCheckPermission(value = {"ROOT", "USER:SELECT"}, mode = SaMode.OR)
//    public CommonResult searchById(@Valid @RequestBody SearchUserByIdForm form) {
//        HashMap map = userService.selectById(form.getUserId());
//        return CommonResult.ok(map);
//    }
//
//    @GetMapping("/selectAllUser")
//    @Operation(summary = "查询所有用户")
//    @SaCheckLogin
//    public CommonResult selectAllUser() {
//        ArrayList<HashMap> list = userService.selectAllUser();
//        return CommonResult.ok().put("list", list);
//    }
    @PostMapping("/login")
    @Operation(summary = "登陆系统")
    public CommonResult login(@Valid @RequestBody LoginForm form) {
        Map param = BeanUtil.beanToMap(form);
        Integer userId = userService.login(param);
        CommonResult commonResult = CommonResult.ok().put("result", userId != null ? true : false);
        if (userId != null) {
            StpUtil.setLoginId(userId);
            Set<String> permissions = userService.selectUserPermissions(userId);
            String token = StpUtil.getTokenInfo().getTokenValue();
            commonResult.put("permissions", permissions).put("token", token);
        }
        return commonResult;
    }

    @GetMapping("/logout")
    @Operation(summary = "退出系统")
    public CommonResult logout() {
        StpUtil.logout();
        return CommonResult.ok();
    }

    @GetMapping("/loadUserInfo")
    @Operation(summary = "加载用户基本信息接口")
    public CommonResult loadUserInfo() {
        int userId = StpUtil.getLoginIdAsInt();
        HashMap hashMap = userService.searchUserInfo(userId);
        return CommonResult.ok(hashMap);
    }

    @PostMapping("/selectUserByPage")
    @Operation(summary = "查询用户信息")
    public CommonResult selectUserByPage(@Valid @RequestBody SearchUserByPageForm form) {
        Map<String, Object> map = BeanUtil.beanToMap(form);
        PageUtils pageUtils = userService.selectUserByPage(map);
        return CommonResult.ok().put(CommonResult.RETURN_PAGE, pageUtils);
    }

    @PostMapping("/selectAllUser")
    @Operation(summary = "查询所有用户")
    public CommonResult selectAllUser() {
        ArrayList<HashMap> list = userService.searchAllUser();
        return CommonResult.ok().put("list", list);
    }

    @PostMapping("/selectNameAndDept")
    @Operation(summary = "查询员工姓名和部门名称接口")
    @SaCheckPermission(value = {"ROOT", "USER:SELECT"}, mode = SaMode.OR) /*sweaggerUi测试中显示未提供token*/
    @SaCheckLogin
    public CommonResult selectNameAndDept(@RequestBody @Valid SearchNameAndDeptForm form) {
        Integer userId = form.getId();
        HashMap hashMap = userService.searchNameAndDept(userId);
        return CommonResult.ok(hashMap);
    }

    @PostMapping("/selectById")
    @Operation(summary = "通过id查询用户信息")
    public CommonResult selectById(@RequestBody @Valid SearchUserByIdForm form) {
        HashMap hashMap = userService.searchById(form.getUserId());
        return CommonResult.ok(hashMap);
    }

    @PostMapping("/insert")
    @Operation(summary = "新增用户")
    public CommonResult insert(@RequestBody @Valid InsertUserForm form) { /*成功插入一条后出现的问题:Duplicate entry '0' for key 'tb_user.unq_root'*/
        UserEntity userEntity = new UserEntity();
        userEntity.setUsername(form.getUsername());
        userEntity.setPassword(form.getPassword());
        userEntity.setName(form.getName());
        userEntity.setSex(form.getSex());
        userEntity.setTel(form.getTel());
        userEntity.setEmail(form.getEmail());
        //先将数组转化成json数组再转成json字符串
        JSONArray json = JSONUtil.parseArray(form.getRole());
        userEntity.setRole(json.toString());
        userEntity.setDeptId(form.getDeptId());
        userEntity.setStatus((byte) 1); //手动将状态设为在职
        userEntity.setCreateTime(new Date()); //  设置创建时间

        int rows = userService.insert(userEntity);

        return CommonResult.ok().put(CommonResult.RETURN_ROW, rows);
    }

    @PostMapping("/update")
    @Operation(summary = "更新用户")
    public CommonResult update(@RequestBody @Valid UpdateUserForm form) {
        JSONArray jsonArray = JSONUtil.parseArray(form.getRole());
        Map<String, Object> map = BeanUtil.beanToMap(form);
        map.put("role", jsonArray.toString());
        map.put("status",1);
        int rows = userService.update(map);
        return CommonResult.ok().put(CommonResult.RETURN_ROW, rows);
    }

    @PostMapping("/deleteUserByIds")
    @Operation(summary = "删除用户接口")
    public CommonResult deleteUserByIds(@RequestBody @Valid DeleteUserByIdsForm form) {
        int rows = userService.deleteUserByIds(form.getIds());
        return CommonResult.ok().put(CommonResult.RETURN_ROW, rows);
    }

    @PostMapping("/updatePassword")
    @Operation(summary = "修改密码接口")
    @SaCheckLogin
    public CommonResult updatePassword(@RequestBody @Valid UpdatePasswordForm form) {
        Map<String, Object> map = BeanUtil.beanToMap(form);
        map.put("userId", StpUtil.getLoginIdAsInt());

        int rows = userService.updatePassword(map);

        return CommonResult.ok().put(CommonResult.RETURN_ROW, rows);
    }
}

